*--------------------------虚拟变量--------------------------
use "E:\同步空间\EDUCATION\Economics\Econometrics\Introductory Econometrics A Modern Approach_Wooldrige\stata伍德里奇\WAGE1.DTA", clear

**虚拟变量分组功能检验--系数的计算
reg wage female                        //总方程1，其中female=1 , if 女性
    *β_female=-2.51183
    ttest wage , by(female)
    *mean_wage_f=4.587659;    mean_wage_m=7.099489
	di 4.587659-7.099489               //β_female=mean_wage_f-mean_wage_m



**虚拟变量分组功能检验--分组方式进入回归
reg wage female educ                   //总方程1，其中female=1 , if 女性
    *使用FWL定理
    reg wage female                      //计算u1
	predict u1,residual
    reg educ female                      //计算u2
	predict u2,residual
	reg u1 u2                            //FWL定理,β_u2=0.5064521
	
	*检验残差 u_t=Y_t-mean_Y_t, u_c=Y_c-mean_Y_c
	gen wage_f=wage-4.587659             //if female=1 , 则 u1=wage-mean_wage_f
	replace wage_f=wage-7.099489 if female==0
    ttest educ , by(female)              //mean_edu_f=12.31746;    mean_edu_m=12.78832
	gen edu_f=educ-12.31746              //if female=1 , 则 u2=educ-mean_educ_f
	replace edu_f=educ-12.78832   if female==0
    reg wage_f edu_f                     //β_edu_f=β_u2=0.5064521
	
**虚拟变量图示
    twoway (scatter wage educ if female==1) (lfit wage educ if female==1) (scatter wage educ if female==0) (lfit wage educ if female==0)
	
**虚拟变量=固定效应
reghdfe wage educ , absorb( female)                


**虚拟变量的交互
reghdfe wage i.married##i.female , noabsorb             
gen newv=married*female
reg wage married female newv   


*-------------------------异方差--------------------------
reg wage female educ                    //不考虑异方差情形，假设误差项独立同分布
reg wage female educ, r                 //异方差-稳健标准误，允许协方差矩阵对角线元素不同
reg wage female educ, cl(smsa)          //聚类-稳健标准误，允许协方差矩阵对角线元素不同、且聚类层面内非对角线元素不为0

 
**加权最小二乘法(WLS)
quietly: reg wage female educ            //总方程1，其中female=1 , if 女性
	   predict u , residual              //求残差
	   twoway (scatter u educ)           //图示u的方差与educ之间的关系，大致发现u的方差与educ成正比关系
	   gen sqrt_educ=sqrt(educ)
reg wage female educ [aw=1/sqrt_educ]    //按照1/sqrt_educ为权重，进行加权最小二乘法估计
       *手动计算
	   gen wage_n=wage/sqrt_educ         //手动计算
	   gen female_n=female/sqrt_educ
       gen educ_n=educ/sqrt_educ
reg wage_n female_n educ_n

**广义加权最小二乘法(FLS)
       
       gen u_sqr=u^2                     //生产残差平方
       gen lnu_sqr=ln(u_sqr)             //取对数
       reg lnu_sqr female educ           //再回归
       predict lnu_sqr_hat ,xb           //求拟合值       
       gen u_hat=exp(lnu_sqr_hat)        //去对数
reg wage female educ [aw=1/u_hat]        //按照1/u_hat为权重，进行加权最小二乘法估计
	
	
	